package com.gxkj.qiao.controllers;

import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.Producer;
import com.aliyun.openservices.ons.api.SendResult;
import com.aliyun.openservices.ons.api.exception.ONSClientException;
import com.gxkj.common.dto.ReturnData;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

@Controller
@RequestMapping("/qiao/message")
public class MessageController {
    Logger LOG = LoggerFactory.getLogger(MessageController.class);
//http://localhost:8088/myshopspark/qiao/message/2ons?topic=bigdata&tag=TagA&key=ORDERID_100&msgString=12345
    @Autowired
    Producer producer ;

    @RequestMapping(value="2ons",method= RequestMethod.POST)
    @ResponseBody
    public ReturnData<String> forward(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap , String topic, String tag, String key){


        if(StringUtils.isBlank(topic)){
            ReturnData data = new ReturnData();
            data.setStatusCode("1");
            data.setEntity("topic cannot be null");
            return data;
        }

        if(StringUtils.isBlank(tag)){
            tag = "";
        }
        if(StringUtils.isBlank(key)){
            key = "";
        }

        String msgString = request.getParameter("msgString");
        Message msg = new Message( //
                // Message Topic
                topic,
                // Message Tag 可理解为Gmail中的标签，对消息进行再归类，方便Consumer指定过滤条件在MQ服务器过滤
                tag,
                // Message Body 可以是任何二进制形式的数据， MQ不做任何干预
                // 需要Producer与Consumer协商好一致的序列化和反序列化方式
                msgString.getBytes());

        // 设置代表消息的业务关键属性，请尽可能全局唯一
        // 以方便您在无法正常收到消息情况下，可通过MQ 控制台查询消息并补发
        // 注意：不设置也不会影响消息正常收发
        msg.setKey(key);
        // 发送消息，只要不抛异常就是成功
        try {
            SendResult sendResult = producer.send(msg);
            assert sendResult != null;
            LOG.info( "send success: " + sendResult.getMessageId());
        }catch (ONSClientException e) {
            LOG.info("发送失败");
        }

        ReturnData data = new ReturnData();
        data.setStatusCode("0");
        data.setEntity("ok");
        return data;
    }
}
